import { getToken, setToken, removeToken } from '@/utils/auth'
// 获取token
import { loginAPI } from '@/api/user'
// 获取用户个人信息
import { userInfoAPI } from '@/api/user'
// 引入静态路由
import { constantRoutes } from '@/router/index'
// 引入重置路由的方法
import { resetRouter } from '@/router/index'

const state = {
  token: getToken(),
  userInfo: {},
  routes: constantRoutes
}

const mutations = {
  // token
  SET_TOKEN(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  REMOVE_TOKEN(state) {
    state.token = null
    removeToken()
  },
  // 用户信息
  SET_USER_INFO(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  }
}

const actions = {
  // token
  async getToken(context, data) {
    const { mobile, password } = data
    const token = await loginAPI({ mobile, password })
    context.commit('SET_TOKEN', token)
  },
  // 用户信息
  async getUserInfo(context) {
    const res = await userInfoAPI()
    context.commit('SET_USER_INFO', res)
    return res
  },
  // token失效时清除用户相关信息
  removeUserInfo(context) {
    context.commit('REMOVE_TOKEN')
    context.commit('SET_USER_INFO', {})
    // 每次用户登出时都把所拥有的路由权限重置
    resetRouter()
  }
}

export default {
  // 开启命名空间
  namespaced: true,
  state,
  mutations,
  actions
}
